<template>
  <div class="business-material-container">
    <!-- 顶部操作栏 -->
    <div class="header-toolbar">
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索框 -->
          <el-input
            v-model="searchKeyword"
            placeholder="搜索素材标题或内容..."
            clearable
            prefix-icon="el-icon-search"
            @input="handleQuickSearch"
            @clear="clearSearch"
            @keyup.enter.native="handleSearch"
          />
        </el-col>

        <el-col :span="4">
          <!-- 素材类型筛选 -->
          <el-select v-model="filterType" placeholder="素材类型" clearable @change="handleSearch">
            <el-option label="全部类型" value="" />
            <el-option label="图片" value="image" />
            <el-option label="视频" value="video" />
            <el-option label="文本" value="text" />
            <el-option label="文档" value="document" />
            <el-option label="音频" value="audio" />
          </el-select>
        </el-col>

        <el-col :span="4">
          <!-- 排序方式 -->
          <el-select v-model="sortBy" placeholder="排序方式" @change="handleSearch">
            <el-option label="智能排序" value="smart" />
            <el-option label="最新优先" value="newest" />
            <el-option label="最常使用" value="most_used" />
          </el-select>
        </el-col>

        <el-col :span="8" style="text-align: right;">
          <el-button type="primary" icon="el-icon-plus" @click="toggleQuickAdd">{{ showQuickAdd ? '隐藏' : '新增素材' }}</el-button>
          <el-button icon="el-icon-setting" @click="showStageDialog">阶段管理</el-button>
          <el-button
            :loading="renewingLinks"
            style="background-color: #1EB7E6; border-color: #1EB7E6; color: white;"
            @click="showLinkRenewalDialog"
          >
            <i class="el-icon-refresh" />
            {{ renewingLinks ? '重新生成中...' : '重新生成链接' }}
          </el-button>
          <el-button icon="el-icon-refresh" @click="handleSearch">刷新</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 主体内容区 -->
    <div class="main-content">
      <el-row :gutter="20">
        <!-- 左侧：业务阶段导航 -->
        <el-col :span="4">
          <div class="stage-sidebar">
            <h3>业务阶段</h3>
            <el-menu
              :default-active="currentStageId"
              @select="handleStageSelect"
            >
              <el-menu-item index="">
                <i class="el-icon-files" />
                <span>全部素材</span>
              </el-menu-item>
              <el-menu-item
                v-for="stage in businessStages"
                :key="stage.id"
                :index="String(stage.id)"
              >
                <i class="el-icon-folder" />
                <span>{{ stage.name }}</span>
              </el-menu-item>
            </el-menu>

            <!-- 标签云 -->
            <div class="tag-cloud">
              <h3>标签筛选</h3>
              <el-tag
                v-for="tag in materialTags"
                :key="tag.id"
                :type="selectedTags.includes(tag.id) ? '' : 'info'"
                :effect="selectedTags.includes(tag.id) ? 'dark' : 'plain'"
                size="small"
                style="margin: 2px; cursor: pointer;"
                @click="toggleTag(tag.id)"
              >
                {{ tag.tag_name }}
                <span v-if="tag.material_count">({{ tag.material_count }})</span>
              </el-tag>
            </div>
          </div>
        </el-col>

        <!-- 中间：素材网格展示 -->
        <el-col :span="16">
          <div v-loading="loading" class="material-grid">
            <!-- 搜索结果提示 -->
            <div v-if="searchKeyword && !loading" class="search-results-header">
              <h4>
                <i class="el-icon-search" />
                {{ quickSearchResults.length > 0 ? `找到 ${quickSearchResults.length} 个相关素材` : '未找到相关素材' }}
                <el-button
                  v-if="quickSearchResults.length > 0"
                  type="text"
                  size="small"
                  @click="clearSearch"
                >
                  清除搜索
                </el-button>
              </h4>
            </div>

            <!-- 快速搜索结果展示 -->
            <div v-if="searchKeyword && quickSearchResults.length > 0" class="quick-search-results">
              <el-row :gutter="15">
                <el-col
                  v-for="item in quickSearchResults"
                  :key="'search-' + item.id"
                  :xs="24"
                  :sm="12"
                  :md="8"
                  :lg="6"
                >
                  <div class="search-result-card" @click="viewMaterial(item)">
                    <div class="result-thumbnail">
                      <!-- 图片缩略图 -->
                      <img v-if="item.thumbnail && (item.material_type === 'image' || item.material_type === 'video')" :src="item.thumbnail" alt="">
                      <!-- 视频没有缩略图时显示播放按钮 -->
                      <div v-else-if="item.material_type === 'video' && !item.thumbnail" class="video-placeholder">
                        <i class="el-icon-video-play" />
                        <span>视频</span>
                      </div>
                      <!-- 文字内容预览 -->
                      <div v-else-if="item.material_type === 'text' && item.content" class="text-preview">
                        {{ getTextPreview(item.content, 100) }}
                      </div>
                      <!-- 其他类型显示图标 -->
                      <i v-else :class="getMaterialIcon(item.material_type)" />
                    </div>
                    <div class="result-info">
                      <div class="result-title">{{ item.title }}</div>
                      <div class="result-meta">
                        <el-tag size="mini" type="info">{{ item.material_type }}</el-tag>
                        <span v-if="item.business_stage_name" class="stage-name">{{ item.business_stage_name }}</span>
                      </div>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>

            <!-- 分隔线 -->
            <el-divider v-if="searchKeyword && quickSearchResults.length > 0" />

            <!-- 推荐素材 -->
            <div v-if="recommendations.length && !searchKeyword" class="recommendations-section">
              <h4><i class="el-icon-star-off" /> 推荐素材</h4>
              <el-row :gutter="10">
                <el-col
                  v-for="item in recommendations"
                  :key="'rec-' + item.id"
                  :span="4"
                >
                  <div class="material-card mini" @click="viewMaterial(item)">
                    <div class="material-thumbnail">
                      <!-- 图片/视频缩略图 -->
                      <img v-if="item.thumbnail && (item.material_type === 'image' || item.material_type === 'video')" :src="item.thumbnail">
                      <!-- 视频没有缩略图时显示播放按钮 -->
                      <div v-else-if="item.material_type === 'video' && !item.thumbnail" class="video-placeholder mini">
                        <i class="el-icon-video-play" />
                      </div>
                      <!-- 文字内容预览 -->
                      <div v-else-if="item.material_type === 'text' && item.content" class="text-preview mini">
                        {{ getTextPreview(item.content) }}
                      </div>
                      <!-- 其他类型显示图标 -->
                      <i v-else :class="getMaterialIcon(item.material_type)" />
                    </div>
                    <div class="material-title">{{ item.title }}</div>
                  </div>
                </el-col>
              </el-row>
            </div>

            <!-- 素材列表 -->
            <draggable
              v-model="materials"
              :options="dragOptions"
              class="material-list"
              @end="handleDragEnd"
            >
              <div
                v-for="material in materials"
                :key="material.id"
                class="material-card"
                :class="{ favorite: material.user_preference.is_favorite }"
              >
                <!-- 收藏标记 -->
                <div v-if="material.user_preference.is_favorite" class="favorite-mark">
                  <i class="el-icon-star-on" />
                </div>

                <!-- 素材内容 -->
                <div class="material-content" @click="viewMaterial(material)">
                  <!-- 缩略图/图标 -->
                  <div class="material-thumbnail">
                    <!-- 图片/视频缩略图 -->
                    <img v-if="material.thumbnail && (material.material_type === 'image' || material.material_type === 'video')" :src="material.thumbnail">
                    <!-- 视频没有缩略图时显示播放按钮 -->
                    <div v-else-if="material.material_type === 'video' && !material.thumbnail" class="video-placeholder">
                      <i class="el-icon-video-play" style="font-size: 32px; color: #409eff;" />
                      <span style="margin-top: 8px; color: #606266; font-size: 12px;">视频素材</span>
                    </div>
                    <!-- 文字内容预览 -->
                    <div v-else-if="material.material_type === 'text' && material.content" class="text-preview">
                      {{ getTextPreview(material.content) }}
                    </div>
                    <!-- 其他类型显示图标 -->
                    <i v-else :class="getMaterialIcon(material.material_type)" style="font-size: 48px;" />
                  </div>

                  <!-- 素材信息 -->
                  <div class="material-info">
                    <h4>{{ material.title }}</h4>
                    <p class="material-meta">
                      <span>{{ material.business_stage_name || '未分类' }}</span>
                      <span>{{ material.material_type }}</span>
                      <span>使用{{ material.user_preference.use_count }}次</span>
                    </p>
                    <div class="material-tags">
                      <el-tag
                        v-for="tag in material.tags"
                        :key="tag.id"
                        size="mini"
                        type="info"
                      >
                        {{ tag.tag_name }}
                      </el-tag>
                    </div>
                  </div>
                </div>

                <!-- 快捷操作 -->
                <div class="material-actions">
                  <el-button
                    :icon="material.user_preference.is_favorite ? 'el-icon-star-on' : 'el-icon-star-off'"
                    circle
                    size="mini"
                    @click="toggleFavorite(material)"
                  />
                  <el-button
                    icon="el-icon-edit"
                    circle
                    size="mini"
                    @click="editMaterial(material)"
                  />
                  <el-button
                    icon="el-icon-delete"
                    circle
                    size="mini"
                    type="danger"
                    @click="deleteMaterial(material)"
                  />
                </div>
              </div>
            </draggable>

            <!-- 空状态 -->
            <div v-if="!loading && materials.length === 0" class="empty-state">
              <i class="el-icon-folder-opened" style="font-size: 60px; color: #C0C4CC; margin-bottom: 10px;" />
              <p style="color: #909399;">暂无素材</p>
              <el-button type="primary" size="small" @click="toggleQuickAdd">立即创建</el-button>
            </div>

            <!-- 分页 -->
            <el-pagination
              v-if="total > pageSize"
              :current-page="currentPage"
              :page-size="pageSize"
              :total="total"
              layout="total, prev, pager, next"
              style="margin-top: 20px; text-align: center;"
              @current-change="handlePageChange"
            />

            <!-- 快速添加素材区域 -->
            <div v-if="showQuickAdd" class="quick-add-section">
              <div class="quick-add-header">
                <h3><i class="el-icon-edit" /> 快速添加素材</h3>
                <div class="quick-add-actions">
                  <el-button type="primary" size="small" @click="quickSaveMaterial">
                    <i class="el-icon-check" /> 保存素材
                  </el-button>
                  <el-button size="small" @click="clearQuickEditor">
                    <i class="el-icon-delete" /> 清空
                  </el-button>
                </div>
              </div>
              <div class="quick-add-form">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-input
                      v-model="quickMaterialForm.title"
                      placeholder="素材标题"
                      clearable
                    />
                  </el-col>
                  <el-col :span="8">
                    <el-select v-model="quickMaterialForm.business_stage_id" placeholder="选择业务阶段" clearable>
                      <el-option
                        v-for="stage in businessStages"
                        :key="stage.id"
                        :label="stage.name"
                        :value="stage.id"
                      />
                    </el-select>
                  </el-col>
                  <el-col :span="8">
                    <el-select
                      v-model="quickMaterialForm.tag_names"
                      multiple
                      filterable
                      allow-create
                      placeholder="选择或创建标签"
                    >
                      <el-option
                        v-for="tag in materialTags"
                        :key="tag.id"
                        :label="tag.tag_name"
                        :value="tag.tag_name"
                      />
                    </el-select>
                  </el-col>
                </el-row>
              </div>
              <div class="quick-add-editor">
                <tiptap-editor
                  ref="quickEditor"
                  v-model="quickMaterialForm.content"
                  placeholder="在这里输入文字、粘贴图片或插入视频..."
                  :upload-url="uploadUrl"
                  directory-name="businessMaterial"
                  @upload-complete="handleQuickEditorUpload"
                />
              </div>
            </div>
          </div>
        </el-col>

        <!-- 右侧：个人收藏 -->
        <el-col :span="4">
          <div class="favorite-sidebar">
            <h3><i class="el-icon-star-on" /> 我的收藏</h3>
            <div class="favorite-list">
              <div
                v-for="item in favoriteMaterials"
                :key="item.id"
                class="favorite-item"
                @click="viewMaterial(item)"
              >
                <i :class="getMaterialIcon(item.material_type)" />
                <span>{{ item.title }}</span>
              </div>
              <div v-if="favoriteMaterials.length === 0" class="empty-state-small">
                <i class="el-icon-star-off" style="font-size: 40px; color: #C0C4CC;" />
                <p style="color: #909399; font-size: 12px; margin-top: 5px;">暂无收藏</p>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 业务阶段管理对话框 -->
    <el-dialog title="业务阶段管理" :visible.sync="stageDialogVisible" width="600px">
      <div class="stage-management">
        <el-button type="primary" size="small" style="margin-bottom: 10px;" @click="showAddStageDialog">
          <i class="el-icon-plus" /> 新增阶段
        </el-button>
        <el-table :data="businessStages" style="width: 100%">
          <el-table-column prop="name" label="阶段名称">
            <template slot-scope="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="sort_order" label="排序" width="120">
            <template slot-scope="scope">
              <el-input-number
                v-model="scope.row.sort_order"
                :min="0"
                :max="9999"
                size="mini"
                @change="updateStageSort(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button size="mini" @click="editStage(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="deleteStage(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 新增/编辑阶段对话框 -->
    <el-dialog
      :title="stageForm.id ? '编辑业务阶段' : '新增业务阶段'"
      :visible.sync="addStageDialogVisible"
      width="400px"
    >
      <el-form ref="stageForm" :model="stageForm" :rules="stageRules" label-width="100px">
        <el-form-item label="阶段名称" prop="name">
          <el-input v-model="stageForm.name" placeholder="请输入阶段名称" />
        </el-form-item>
        <el-form-item label="排序值" prop="sort_order">
          <el-input-number
            v-model="stageForm.sort_order"
            :min="0"
            :max="9999"
            placeholder="数字越小越靠前"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addStageDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveStage">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 素材查看/编辑抽屉 -->
    <el-drawer
      :title="isEditMode ? '编辑素材' : '查看素材'"
      :visible.sync="editDrawerVisible"
      direction="rtl"
      size="90%"
      :close-on-press-escape="true"
      :wrapper-closable="false"
    >
      <div class="material-drawer-content">
        <!-- 头部：标题和操作按钮 -->
        <div class="drawer-header">
          <div class="title-section">
            <el-input
              v-if="isEditMode"
              v-model="editForm.title"
              placeholder="请输入素材标题"
              size="large"
              class="title-input"
              :maxlength="100"
              show-word-limit
            />
            <h2 v-else class="title-display">{{ editForm.title }}</h2>
          </div>

          <div class="header-actions">
            <el-button
              v-if="!isEditMode"
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="toggleEditMode"
            >
              编辑
            </el-button>
            <template v-else>
              <el-button size="small" @click="cancelEdit">取消</el-button>
              <el-button
                type="primary"
                :loading="saving"
                size="small"
                @click="saveEditMaterial"
              >
                保存
              </el-button>
            </template>
          </div>
        </div>

        <!-- 次要信息栏 -->
        <div class="meta-info-bar">
          <div class="meta-left">
            <el-tag size="mini" :type="editForm.material_type === 'text' ? '' : 'success'">
              {{ editForm.material_type === 'text' ? '文本' : editForm.material_type === 'image' ? '图片' : editForm.material_type === 'video' ? '视频' : '其他' }}
            </el-tag>

            <el-select
              v-if="isEditMode"
              v-model="editForm.business_stage_id"
              placeholder="业务阶段"
              clearable
              size="mini"
              class="mini-select"
            >
              <el-option
                v-for="stage in businessStages"
                :key="stage.id"
                :label="stage.name"
                :value="stage.id"
              />
            </el-select>
            <span v-else class="meta-item">
              <i class="el-icon-folder" />
              {{ getBusinessStageName(editForm.business_stage_id) || '未分类' }}
            </span>
          </div>

          <div class="meta-right">
            <el-select
              v-if="isEditMode"
              v-model="editForm.tag_names"
              multiple
              filterable
              allow-create
              placeholder="标签"
              size="mini"
              class="mini-select tags-select"
            >
              <el-option
                v-for="tag in materialTags"
                :key="tag.id"
                :label="tag.tag_name"
                :value="tag.tag_name"
              />
            </el-select>
            <div v-else class="tags-display">
              <el-tag
                v-for="tagId in editForm.tag_ids"
                :key="tagId"
                size="mini"
                type="info"
              >
                {{ getTagName(tagId) }}
              </el-tag>
              <span v-if="!editForm.tag_ids || editForm.tag_ids.length === 0" class="no-tags">无标签</span>
            </div>
          </div>
        </div>

        <!-- 图片缩略图栏 -->
        <div v-if="contentImages.length > 0" class="image-thumbnail-bar">
          <div class="thumbnail-container">
            <div
              v-for="(image, index) in contentImages"
              :key="index"
              class="thumbnail-item"
              @click="openImageViewer(index)"
              @mouseenter="onThumbnailHover"
              @mouseleave="onThumbnailLeave"
            >
              <img :src="image.src" :alt="image.alt || '图片'">
              <div class="thumbnail-overlay">
                <i class="el-icon-zoom-in" />
              </div>
            </div>
          </div>
        </div>

        <!-- 图片查看器 -->
        <el-dialog
          :visible.sync="imageViewerVisible"
          :show-close="false"
          :close-on-click-modal="true"
          :close-on-press-escape="true"
          :append-to-body="true"
          width="90%"
          custom-class="image-viewer-dialog"
          center
        >
          <div class="image-viewer">
            <div class="viewer-header">
              <span class="image-counter">{{ currentImageIndex + 1 }} / {{ contentImages.length }}</span>
              <el-button
                type="text"
                icon="el-icon-close"
                class="close-btn"
                @click="closeImageViewer"
              />
            </div>

            <div class="viewer-content">
              <el-button
                v-if="contentImages.length > 1"
                type="text"
                icon="el-icon-arrow-left"
                class="nav-btn prev-btn"
                :disabled="currentImageIndex === 0"
                @click="previousImage"
              />

              <div class="image-container">
                <img
                  v-if="currentImage"
                  :src="currentImage.src"
                  :alt="currentImage.alt || '图片'"
                  class="main-image"
                >
              </div>

              <el-button
                v-if="contentImages.length > 1"
                type="text"
                icon="el-icon-arrow-right"
                class="nav-btn next-btn"
                :disabled="currentImageIndex === contentImages.length - 1"
                @click="nextImage"
              />
            </div>
          </div>
        </el-dialog>

        <!-- 主要内容区 -->
        <div class="content-area">
          <!-- 内容主体 -->
          <div class="content-main">
            <tiptap-editor
              v-if="isEditMode"
              ref="editEditor"
              v-model="editForm.content"
              placeholder="开始编写素材内容..."
              :upload-url="uploadUrl"
              directory-name="businessMaterial"
              class="drawer-editor"
              @upload-complete="handleEditEditorUpload"
            />
            <div v-else class="content-display" v-html="editForm.content" />
          </div>

          <!-- 大纲侧边栏 -->
          <div v-if="!isEditMode && contentOutline.length > 0" class="content-outline">
            <div class="outline-header">
              <i class="el-icon-menu" />
              <span>大纲</span>
            </div>
            <div class="outline-list">
              <div
                v-for="item in contentOutline"
                :key="item.id"
                :class="['outline-item', `outline-level-${item.level}`]"
                @click="scrollToHeading(item.id)"
              >
                <span class="outline-text">{{ item.text }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>

  </div>
</template>

<script>
import draggable from 'vuedraggable'
import TiptapEditor from '@/components/TiptapEditor'
import {
  getBusinessStages,
  createBusinessStage,
  updateBusinessStage,
  deleteBusinessStage,
  getBusinessMaterials,
  getBusinessMaterial,
  createBusinessMaterial,
  updateBusinessMaterial,
  deleteBusinessMaterial,
  setMaterialPreference,
  batchUpdateMaterialSort,
  quickSearchMaterials,
  getMaterialRecommendations,
  getMaterialTags
} from '@/api/businessMaterial'

export default {
  name: 'BusinessMaterial',
  components: {
    draggable,
    TiptapEditor
  },
  data() {
    return {
      // 搜索和筛选
      searchKeyword: '',
      filterType: '',
      sortBy: 'smart',
      currentStageId: '',
      selectedTags: [],
      quickSearchResults: [],

      // 数据列表
      materials: [],
      favoriteMaterials: [],
      recommendations: [],
      businessStages: [],
      materialTags: [],

      // 分页
      currentPage: 1,
      pageSize: 20,
      total: 0,

      // 对话框
      stageDialogVisible: false,
      addStageDialogVisible: false,
      showQuickAdd: false,
      editDrawerVisible: false,
      isEditMode: false,
      originalEditForm: {},
      linkRenewalDialogVisible: false,
      renewingLinks: false,

      // 图片查看器
      imageViewerVisible: false,
      currentImageIndex: 0,
      contentImages: [],

      // 阶段表单
      stageForm: {
        id: null,
        name: '',
        sort_order: 0
      },
      stageRules: {
        name: [
          { required: true, message: '请输入阶段名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        sort_order: [
          { required: true, message: '请输入排序值', trigger: 'blur' }
        ]
      },

      // 表单
      materialForm: {
        title: '',
        business_stage_id: null,
        material_type: 'image',
        thumbnail: '',
        content: '',
        tag_ids: []
      },

      // 快速添加素材表单
      quickMaterialForm: {
        title: '',
        business_stage_id: null,
        content: '',
        tag_names: []
      },

      // 编辑素材表单
      editForm: {
        id: null,
        title: '',
        business_stage_id: null,
        content: '',
        tag_ids: [],
        tag_names: [],
        material_type: 'text'
      },

      // 内容大纲
      contentOutline: [],

      // 表单验证
      materialRules: {
        title: [
          { required: true, message: '请输入素材标题', trigger: 'blur' }
        ],
        material_type: [
          { required: true, message: '请选择素材类型', trigger: 'change' }
        ]
      },

      // 其他
      loading: false,
      saving: false,
      uploadUrl: process.env.VUE_APP_BASE_API + '/api/upload/material/',
      dragOptions: {
        animation: 200,
        group: 'materials',
        disabled: false,
        ghostClass: 'ghost'
      }
    }
  },

  computed: {
    // 当前查看的图片
    currentImage() {
      return this.contentImages[this.currentImageIndex] || null
    }
  },

  watch: {
    // 监听editForm.content的变化，提取图片
    'editForm.content': {
      handler(newContent) {
        this.extractImagesFromContent(newContent)
      },
      immediate: true
    }
  },

  mounted() {
    this.init()
  },

  methods: {
    // 初始化
    async init() {
      await this.loadBusinessStages()
      await this.loadMaterialTags()
      await this.loadMaterials()
      await this.loadRecommendations()
    },

    // 加载业务阶段
    async loadBusinessStages() {
      try {
        const res = await getBusinessStages()
        if (res.success) {
          this.businessStages = res.data
        }
      } catch (error) {
        console.error('加载业务阶段失败', error)
      }
    },

    // 加载标签
    async loadMaterialTags() {
      try {
        const res = await getMaterialTags()
        if (res.success) {
          this.materialTags = res.data
        }
      } catch (error) {
        console.error('加载标签失败', error)
      }
    },

    // 加载素材列表
    async loadMaterials() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          page_size: this.pageSize,
          sort: this.sortBy
        }

        if (this.currentStageId) {
          params.stage_id = this.currentStageId
        }

        if (this.filterType) {
          params.type = this.filterType
        }

        if (this.selectedTags.length) {
          params.tag_ids = this.selectedTags
        }

        if (this.searchKeyword) {
          params.keyword = this.searchKeyword
        }

        const res = await getBusinessMaterials(params)
        if (res.success) {
          this.materials = res.data
          this.total = res.total

          // 提取收藏的素材
          this.favoriteMaterials = res.data.filter(m => m.user_preference.is_favorite)
        }
      } catch (error) {
        this.$message.error('加载素材失败')
        console.error(error)
      } finally {
        this.loading = false
      }
    },

    // 加载推荐素材
    async loadRecommendations() {
      try {
        const params = {
          limit: 5
        }
        if (this.currentStageId) {
          params.stage_id = this.currentStageId
        }

        const res = await getMaterialRecommendations(params)
        if (res.success) {
          this.recommendations = res.data
        }
      } catch (error) {
        console.error('加载推荐失败', error)
      }
    },

    // 快速搜索
    async handleQuickSearch() {
      if (!this.searchKeyword) {
        this.quickSearchResults = []
        return
      }

      try {
        const res = await quickSearchMaterials(this.searchKeyword)
        if (res.success) {
          this.quickSearchResults = res.data
        }
      } catch (error) {
        console.error('快速搜索失败', error)
      }
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.loadMaterials()
    },

    // 清除搜索
    clearSearch() {
      this.searchKeyword = ''
      this.quickSearchResults = []
      this.handleSearch()
    },

    // 阶段选择
    handleStageSelect(stageId) {
      this.currentStageId = stageId
      // 如果快速添加区域正在显示，同步更新业务阶段选择
      if (this.showQuickAdd) {
        this.quickMaterialForm.business_stage_id = stageId || null
      }
      this.handleSearch()
      this.loadRecommendations()
    },

    // 标签切换
    toggleTag(tagId) {
      const index = this.selectedTags.indexOf(tagId)
      if (index > -1) {
        this.selectedTags.splice(index, 1)
      } else {
        this.selectedTags.push(tagId)
      }
      this.handleSearch()
    },

    // 分页
    handlePageChange(page) {
      this.currentPage = page
      this.loadMaterials()
    },

    // 拖拽结束
    async handleDragEnd() {
      // 生成新的排序数据
      const sortData = this.materials.map((item, index) => ({
        material_id: item.id,
        sort: (this.materials.length - index) * 10
      }))

      try {
        await batchUpdateMaterialSort(sortData)
        this.$message.success('排序已更新')
      } catch (error) {
        this.$message.error('更新排序失败')
        console.error(error)
      }
    },

    // 切换收藏
    async toggleFavorite(material) {
      try {
        const res = await setMaterialPreference({
          material_id: material.id,
          is_favorite: !material.user_preference.is_favorite
        })

        if (res.success) {
          material.user_preference.is_favorite = !material.user_preference.is_favorite
          this.$message.success(material.user_preference.is_favorite ? '已收藏' : '已取消收藏')

          // 更新收藏列表
          if (material.user_preference.is_favorite) {
            this.favoriteMaterials.push(material)
          } else {
            const index = this.favoriteMaterials.findIndex(m => m.id === material.id)
            if (index > -1) {
              this.favoriteMaterials.splice(index, 1)
            }
          }
        }
      } catch (error) {
        this.$message.error('操作失败')
        console.error(error)
      }
    },

    // 切换快速添加显示
    toggleQuickAdd() {
      this.showQuickAdd = !this.showQuickAdd
      if (this.showQuickAdd) {
        // 设置默认值：如果当前选择了业务阶段，则自动选择该阶段
        this.quickMaterialForm.business_stage_id = this.currentStageId || null
      }
    },

    // 编辑素材（默认查看模式）
    editMaterial(material) {
      // 填充表单数据
      this.editForm = {
        id: material.id,
        title: material.title,
        business_stage_id: material.business_stage_id,
        content: material.content || '',
        tag_ids: material.tags ? material.tags.map(tag => tag.id) : [],
        tag_names: material.tags ? material.tags.map(tag => tag.tag_name) : [],
        material_type: material.material_type
      }

      // 保存原始数据用于取消编辑
      this.originalEditForm = JSON.parse(JSON.stringify(this.editForm))

      // 默认查看模式
      this.isEditMode = false

      // 打开抽屉
      this.editDrawerVisible = true

      // 生成内容大纲
      this.$nextTick(() => {
        this.generateContentOutline()
      })
    },

    // 切换编辑模式
    toggleEditMode() {
      this.isEditMode = true

      // 等待DOM更新后设置编辑器内容
      this.$nextTick(() => {
        if (this.$refs.editEditor && this.editForm.content) {
          this.$refs.editEditor.editor.commands.setContent(this.editForm.content)
        }
      })
    },

    // 取消编辑
    cancelEdit() {
      // 恢复原始数据
      this.editForm = JSON.parse(JSON.stringify(this.originalEditForm))
      this.isEditMode = false
    },

    // 获取业务阶段名称
    getBusinessStageName(stageId) {
      if (!stageId) return ''
      const stage = this.businessStages.find(s => s.id === stageId)
      return stage ? stage.name : ''
    },

    // 获取标签名称
    getTagName(tagId) {
      const tag = this.materialTags.find(t => t.id === tagId)
      return tag ? tag.tag_name : tagId
    },

    // 删除素材
    deleteMaterial(material) {
      this.$confirm(`确定删除素材"${material.title}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          const res = await deleteBusinessMaterial(material.id)
          if (res.success) {
            this.$message.success('删除成功')
            this.loadMaterials()
          } else {
            this.$message.error(res.msg || '删除失败')
          }
        } catch (error) {
          this.$message.error('删除失败')
          console.error(error)
        }
      }).catch(() => {})
    },

    // 查看素材
    async viewMaterial(material) {
      try {
        // 调用API获取素材详情，后端会自动记录使用次数
        const res = await getBusinessMaterial(material.id)
        if (res.success) {
          // 使用最新的数据打开编辑抽屉
          const updatedMaterial = res.data

          // 更新列表中的使用次数
          const index = this.materials.findIndex(m => m.id === material.id)
          if (index !== -1 && updatedMaterial.user_preference) {
            this.$set(this.materials[index].user_preference, 'use_count', updatedMaterial.user_preference.use_count)
          }

          // 更新快速搜索结果中的使用次数
          const quickIndex = this.quickSearchResults.findIndex(m => m.id === material.id)
          if (quickIndex !== -1 && updatedMaterial.user_preference) {
            this.$set(this.quickSearchResults[quickIndex], 'user_preference', updatedMaterial.user_preference)
          }

          // 更新推荐列表中的使用次数
          const recIndex = this.recommendations.findIndex(m => m.id === material.id)
          if (recIndex !== -1 && updatedMaterial.user_preference) {
            this.$set(this.recommendations[recIndex], 'user_preference', updatedMaterial.user_preference)
          }

          // 打开查看/编辑抽屉
          this.editMaterial(updatedMaterial)
        }
      } catch (error) {
        console.error('获取素材详情失败', error)
        // 如果获取失败，仍然使用本地数据打开
        this.editMaterial(material)
      }
    },

    // 显示阶段管理对话框
    showStageDialog() {
      this.stageDialogVisible = true
    },

    // 显示新增阶段对话框
    showAddStageDialog() {
      this.stageForm = {
        id: null,
        name: '',
        sort_order: this.businessStages.length ? Math.max(...this.businessStages.map(s => s.sort_order || 0)) + 10 : 10
      }
      this.addStageDialogVisible = true
    },

    // 编辑阶段（使用新的对话框方式）
    editStage(stage) {
      this.stageForm = {
        id: stage.id,
        name: stage.name,
        sort_order: stage.sort_order || 0
      }
      this.addStageDialogVisible = true
    },

    // 保存阶段（新增或编辑）
    async saveStage() {
      this.$refs.stageForm.validate(async valid => {
        if (valid) {
          try {
            let res
            if (this.stageForm.id) {
              // 编辑
              res = await updateBusinessStage(this.stageForm.id, {
                name: this.stageForm.name,
                sort_order: this.stageForm.sort_order
              })
            } else {
              // 新增
              res = await createBusinessStage({
                name: this.stageForm.name,
                sort_order: this.stageForm.sort_order
              })
            }

            if (res.success) {
              this.$message.success(this.stageForm.id ? '更新成功' : '创建成功')
              this.addStageDialogVisible = false
              this.loadBusinessStages()
            } else {
              this.$message.error(res.msg || (this.stageForm.id ? '更新失败' : '创建失败'))
            }
          } catch (error) {
            console.error('保存阶段失败:', error)
            this.$message.error(this.stageForm.id ? '更新失败' : '创建失败')
          }
        }
      })
    },

    // 更新阶段排序
    async updateStageSort(stage) {
      try {
        const res = await updateBusinessStage(stage.id, {
          name: stage.name,
          sort_order: stage.sort_order
        })
        if (res.success) {
          this.$message.success('排序更新成功')
          // 重新加载列表以确保排序正确
          this.loadBusinessStages()
        } else {
          this.$message.error(res.msg || '排序更新失败')
          this.loadBusinessStages() // 恢复原值
        }
      } catch (error) {
        console.error('更新排序失败:', error)
        this.$message.error('排序更新失败')
        this.loadBusinessStages() // 恢复原值
      }
    },

    // 删除阶段
    async deleteStage(stage) {
      try {
        await this.$confirm(`确定删除阶段"${stage.name}"吗？`, '提示')
        const res = await deleteBusinessStage(stage.id)
        if (res.success) {
          this.$message.success('删除成功')
          this.loadBusinessStages()
        }
      } catch (error) {
        console.log('取消删除')
      }
    },

    // 文件上传前
    beforeUpload(file) {
      const isLt1G = file.size / 1024 / 1024 / 1024 < 1
      if (!isLt1G) {
        this.$message.error('文件大小不能超过 1GB!')
      }
      return isLt1G
    },

    // 上传成功
    handleUploadSuccess(response, file) {
      if (response.success) {
        this.materialForm.thumbnail = response.data.thumbnail || response.data.url
        this.$message.success('上传成功')
      }
    },

    // 上传失败
    handleUploadError() {
      this.$message.error('上传失败')
    },

    // 获取素材图标
    getMaterialIcon(type) {
      const icons = {
        image: 'el-icon-picture',
        video: 'el-icon-video-camera',
        text: 'el-icon-document',
        document: 'el-icon-document-copy',
        audio: 'el-icon-headset'
      }
      return icons[type] || 'el-icon-document'
    },

    // 获取上传提示
    getUploadTip(type) {
      const tips = {
        image: '支持 jpg/png/gif 格式，大小不超过 1GB',
        video: '支持 mp4/avi/mov 格式，大小不超过 1GB',
        document: '支持 pdf/doc/docx/xls/xlsx 格式，大小不超过 1GB',
        audio: '支持 mp3/wav 格式，大小不超过 1GB'
      }
      return tips[type] || '文件大小不超过 1GB'
    },

    // 快速保存素材
    async quickSaveMaterial() {
      if (!this.quickMaterialForm.title) {
        this.$message.warning('请输入素材标题')
        return
      }

      if (!this.quickMaterialForm.content || this.quickMaterialForm.content === '<p></p>') {
        this.$message.warning('请输入素材内容')
        return
      }

      try {
        // 从编辑器内容中提取素材类型和内容
        const content = this.quickMaterialForm.content
        let materialType = 'text'
        let thumbnail = ''

        // 检测内容类型
        if (content.includes('<img')) {
          materialType = 'image'
          // 提取第一张图片作为文件路径和缩略图
          const imgMatch = content.match(/<img[^>]+src="([^"]+)"/)
          if (imgMatch) {
            thumbnail = imgMatch[1]
          }
        } else if (content.includes('<video') || content.includes('<iframe')) {
          materialType = 'video'
          // 对于视频，保存整个HTML内容
        }

        const materialData = {
          title: this.quickMaterialForm.title,
          business_stage_id: this.quickMaterialForm.business_stage_id,
          material_type: materialType,
          content: content,
          thumbnail: thumbnail,
          tag_names: this.quickMaterialForm.tag_names // 发送标签名称而不是ID
        }

        const res = await createBusinessMaterial(materialData)
        if (res.success) {
          this.$message.success('素材保存成功')
          this.clearQuickEditor()
          this.showQuickAdd = false // 保存成功后隐藏编辑器
          this.loadMaterials()
        } else {
          this.$message.error(res.msg || '保存失败')
        }
      } catch (error) {
        this.$message.error('保存失败')
        console.error(error)
      }
    },

    // 清空快速编辑器
    clearQuickEditor() {
      this.quickMaterialForm = {
        title: '',
        business_stage_id: null,
        content: '',
        tag_names: []
      }
      if (this.$refs.quickEditor) {
        this.$refs.quickEditor.clearContent()
      }
    },

    // 获取文本预览（从HTML内容中提取纯文本）
    getTextPreview(htmlContent, maxLength = 50) {
      if (!htmlContent) return ''

      // 创建临时DOM元素来提取纯文本
      const tempDiv = document.createElement('div')
      tempDiv.innerHTML = htmlContent
      const textContent = tempDiv.textContent || tempDiv.innerText || ''

      // 返回指定长度的字符作为预览
      return textContent.length > maxLength ? textContent.substring(0, maxLength) + '...' : textContent
    },

    // 保存编辑的素材
    async saveEditMaterial() {
      if (!this.editForm.title) {
        this.$message.warning('请输入素材标题')
        return
      }

      if (!this.editForm.content || this.editForm.content === '<p></p>') {
        this.$message.warning('请输入素材内容')
        return
      }

      this.saving = true
      try {
        // 从编辑器内容中提取素材类型和内容
        const content = this.editForm.content
        let materialType = 'text'
        let thumbnail = ''

        // 检测内容类型
        if (content.includes('<img')) {
          materialType = 'image'
          // 提取第一张图片作为文件路径和缩略图
          const imgMatch = content.match(/<img[^>]+src="([^"]+)"/)
          if (imgMatch) {
            thumbnail = imgMatch[1]
          }
        } else if (content.includes('<video') || content.includes('<iframe')) {
          materialType = 'video'
        }

        const updateData = {
          title: this.editForm.title,
          business_stage_id: this.editForm.business_stage_id,
          material_type: materialType,
          content: content,
          thumbnail: thumbnail,
          tag_names: this.editForm.tag_names // 发送标签名称而不是ID
        }

        const res = await updateBusinessMaterial(this.editForm.id, updateData)
        if (res.success) {
          this.$message.success('素材更新成功')
          // 更新原始数据并切换到查看模式
          this.originalEditForm = JSON.parse(JSON.stringify(this.editForm))
          this.isEditMode = false
          this.loadMaterials() // 重新加载列表
        } else {
          this.$message.error(res.msg || '更新失败')
        }
      } catch (error) {
        this.$message.error('更新失败')
        console.error(error)
      } finally {
        this.saving = false
      }
    },

    // 显示链接重新生成对话框
    showLinkRenewalDialog() {
      if (this.materials.length === 0) {
        this.$message.info('当前没有素材可以重新生成链接')
        return
      }

      this.$confirm(
        '这将检查所有素材中的图片链接，并将失效或临时链接重新生成为永久链接。是否继续？',
        '重新生成图片链接',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        this.batchRenewMaterialLinks()
      }).catch(() => {
        // 取消操作
      })
    },

    // 批量重新生成素材链接
    async batchRenewMaterialLinks() {
      this.renewingLinks = true

      try {
        // 导入API
        const { batchRenewMaterialLinks } = await import('@/api/cms/image-renewal')

        // 获取当前页面所有素材的ID
        const materialIds = this.materials.map(material => material.id)

        const response = await batchRenewMaterialLinks({ material_ids: materialIds })

        if (response.success) {
          const { total_renewed, total_failed, processed_count } = response.data

          if (total_renewed > 0) {
            this.$notify({
              title: '成功',
              message: `成功处理 ${processed_count} 个素材，重新生成 ${total_renewed} 个链接`,
              type: 'success',
              duration: 4000
            })

            // 刷新列表
            this.handleSearch()
          } else {
            this.$message.info('没有链接需要重新生成')
          }

          if (total_failed > 0) {
            this.$notify({
              title: '警告',
              message: `有 ${total_failed} 个链接重新生成失败`,
              type: 'warning',
              duration: 3000
            })
          }
        } else {
          this.$notify({
            title: '错误',
            message: response.msg || '批量重新生成链接失败',
            type: 'error',
            duration: 3000
          })
        }
      } catch (error) {
        console.error('批量重新生成链接失败:', error)
        this.$notify({
          title: '错误',
          message: '批量重新生成链接失败: ' + (error.message || '网络错误'),
          type: 'error',
          duration: 3000
        })
      } finally {
        this.renewingLinks = false
      }
    },

    // 从内容中提取图片
    extractImagesFromContent(content) {
      if (!content) {
        this.contentImages = []
        return
      }

      const images = []

      // 使用DOM解析器来正确处理HTML实体
      const parser = new DOMParser()
      const doc = parser.parseFromString(content, 'text/html')
      const imgElements = doc.querySelectorAll('img')

      imgElements.forEach(img => {
        // 直接从DOM元素获取属性，会自动处理HTML实体
        const src = img.getAttribute('src')
        const alt = img.getAttribute('alt') || '图片'

        if (src) {
          images.push({
            src: src,
            alt: alt
          })
        }
      })

      this.contentImages = images
    },

    // 图片缩略图hover事件
    onThumbnailHover(event) {
      event.currentTarget.style.transform = 'scale(1.1)'
    },

    onThumbnailLeave(event) {
      event.currentTarget.style.transform = 'scale(1)'
    },

    // 打开图片查看器
    openImageViewer(index) {
      this.currentImageIndex = index
      this.imageViewerVisible = true
    },

    // 关闭图片查看器
    closeImageViewer() {
      this.imageViewerVisible = false
      this.currentImageIndex = 0
    },

    // 上一张图片
    previousImage() {
      if (this.currentImageIndex > 0) {
        this.currentImageIndex--
      }
    },

    // 下一张图片
    nextImage() {
      if (this.currentImageIndex < this.contentImages.length - 1) {
        this.currentImageIndex++
      }
    },

    // 处理快速编辑器上传完成事件
    handleQuickEditorUpload(uploadInfo) {
      console.log('快速编辑器上传完成:', uploadInfo)
      // 自动设置标题（如果没有设置）
      if (!this.quickMaterialForm.title && uploadInfo.file && uploadInfo.file.filename) {
        this.quickMaterialForm.title = uploadInfo.file.filename.replace(/\.[^/.]+$/, '')
      }

      // 自动保存素材
      this.autoSaveQuickMaterial(uploadInfo)
    },

    // 处理详情编辑器上传完成事件
    handleEditEditorUpload(uploadInfo) {
      console.log('详情编辑器上传完成:', uploadInfo)
      // 自动保存素材
      this.autoSaveEditMaterial(uploadInfo)
    },

    // 自动保存快速添加的素材
    async autoSaveQuickMaterial(uploadInfo) {
      // 如果没有标题，不自动保存
      if (!this.quickMaterialForm.title) {
        this.$message.info('已上传文件，请设置标题后手动保存')
        return
      }

      // 如果内容为空，不自动保存
      if (!this.quickMaterialForm.content || this.quickMaterialForm.content === '<p></p>') {
        this.$message.info('内容为空，请添加内容后手动保存')
        return
      }

      try {
        await this.quickSaveMaterial()
        this.$message.success(`${uploadInfo.type === 'batch' ? '批量' : ''}上传完成并自动保存`)
      } catch (error) {
        console.error('自动保存失败:', error)
        this.$message.warning('上传成功，但自动保存失败，请手动保存')
      }
    },

    // 自动保存编辑的素材
    async autoSaveEditMaterial(uploadInfo) {
      // 如果没有标题，不自动保存
      if (!this.editForm.title) {
        this.$message.info('已上传文件，请设置标题后手动保存')
        return
      }

      // 如果内容为空，不自动保存
      if (!this.editForm.content || this.editForm.content === '<p></p>') {
        this.$message.info('内容为空，请添加内容后手动保存')
        return
      }

      try {
        await this.saveEditMaterial()
        this.$message.success(`${uploadInfo.type === 'batch' ? '批量' : ''}上传完成并自动保存`)
      } catch (error) {
        console.error('自动保存失败:', error)
        this.$message.warning('上传成功，但自动保存失败，请手动保存')
      }
    },

    // 生成内容大纲
    generateContentOutline() {
      if (!this.editForm.content) {
        this.contentOutline = []
        return
      }

      const outline = []
      const parser = new DOMParser()
      const doc = parser.parseFromString(this.editForm.content, 'text/html')
      const headings = doc.querySelectorAll('h1, h2, h3, h4, h5, h6')

      headings.forEach((heading, index) => {
        const level = parseInt(heading.tagName.substring(1))
        const text = heading.textContent.trim()
        const id = `heading-${index}`

        // 为标题添加ID以便滚动定位
        heading.setAttribute('id', id)

        if (text) {
          outline.push({
            id: id,
            text: text,
            level: level
          })
        }
      })

      this.contentOutline = outline

      // 更新显示内容的HTML
      this.$nextTick(() => {
        const contentDisplay = document.querySelector('.content-display')
        if (contentDisplay) {
          contentDisplay.innerHTML = doc.body.innerHTML
        }
      })
    },

    // 滚动到指定标题
    scrollToHeading(headingId) {
      const element = document.getElementById(headingId)
      if (element) {
        element.scrollIntoView({
          behavior: 'smooth',
          block: 'start'
        })

        // 高亮效果
        element.style.backgroundColor = '#fff2cc'
        setTimeout(() => {
          element.style.backgroundColor = ''
        }, 2000)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.business-material-container {
  padding: 20px;

  .header-toolbar {
    background: white;
    padding: 15px;
    border-radius: 4px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }

  .main-content {
    .stage-sidebar {
      background: white;
      padding: 15px;
      border-radius: 4px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);

      h3 {
        margin: 0 0 15px 0;
        font-size: 16px;
        color: #333;
      }

      .el-menu {
        border: none;
      }

      .tag-cloud {
        margin-top: 30px;

        h3 {
          margin-bottom: 10px;
        }
      }
    }

    .material-grid {
      background: white;
      padding: 20px;
      border-radius: 4px;
      min-height: 500px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);

      .recommendations-section {
        margin-bottom: 20px;
        padding-bottom: 20px;
        border-bottom: 1px solid #eee;

        h4 {
          margin: 0 0 10px 0;
          color: #666;
        }

        .material-card.mini {
          cursor: pointer;
          text-align: center;
          padding: 10px;

          .material-thumbnail {
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: center;

            img {
              max-width: 100%;
              max-height: 100%;
            }

            i {
              font-size: 32px;
              color: #999;
            }
          }

          .material-title {
            margin-top: 5px;
            font-size: 12px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          &:hover {
            background: #f5f5f5;
            border-radius: 4px;
          }
        }
      }

      .material-list {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 15px;
      }

      .material-card {
        border: 1px solid #e4e4e4;
        border-radius: 4px;
        padding: 10px;
        position: relative;
        transition: all 0.3s;
        cursor: move;

        &:hover {
          box-shadow: 0 4px 8px rgba(0,0,0,0.15);
          transform: translateY(-2px);
        }

        &.favorite {
          border-color: #f56c6c;
        }

        .favorite-mark {
          position: absolute;
          top: 5px;
          right: 5px;
          color: #f56c6c;
        }

        .material-content {
          cursor: pointer;

          .material-thumbnail {
            height: 120px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #f5f5f5;
            border-radius: 4px;
            margin-bottom: 10px;

            img {
              max-width: 100%;
              max-height: 100%;
              object-fit: cover;
            }

            i {
              color: #999;
            }

            .text-preview {
              padding: 10px;
              font-size: 13px;
              line-height: 1.4;
              color: #666;
              text-align: left;
              overflow: hidden;
              text-overflow: ellipsis;
              display: -webkit-box;
              -webkit-line-clamp: 4;
              -webkit-box-orient: vertical;
              word-break: break-word;

              &.mini {
                padding: 5px;
                font-size: 12px;
                -webkit-line-clamp: 2;
              }
            }

            .video-placeholder {
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              height: 100%;
              color: #409eff;

              i {
                font-size: 32px !important;
                margin-bottom: 8px;
                color: #409eff !important;
              }

              span {
                font-size: 12px;
                color: #606266;
                text-align: center;
              }
            }
          }

          .material-info {
            h4 {
              margin: 0 0 5px 0;
              font-size: 14px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            .material-meta {
              font-size: 12px;
              color: #999;
              margin-bottom: 5px;

              span {
                margin-right: 10px;
              }
            }

            .material-tags {
              .el-tag {
                margin-right: 5px;
              }
            }
          }
        }

        .material-actions {
          display: flex;
          justify-content: space-around;
          margin-top: 10px;
          padding-top: 10px;
          border-top: 1px solid #eee;
        }
      }

      .ghost {
        opacity: 0.5;
        background: #c8ebfb;
      }

      .empty-state {
        text-align: center;
        padding: 40px 0;
      }

      .empty-state-small {
        text-align: center;
        padding: 20px 0;
      }
    }

    .favorite-sidebar {
      background: white;
      padding: 15px;
      border-radius: 4px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);

      h3 {
        margin: 0 0 15px 0;
        font-size: 16px;
        color: #333;

        i {
          color: #f56c6c;
        }
      }

      .favorite-list {
        .favorite-item {
          padding: 8px;
          cursor: pointer;
          border-radius: 4px;
          margin-bottom: 5px;

          &:hover {
            background: #f5f5f5;
          }

          i {
            margin-right: 5px;
            color: #999;
          }

          span {
            font-size: 14px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }
    }
  }

  .stage-management {
    .el-table {
      margin-top: 10px;
    }
  }

  .file-preview {
    margin-top: 10px;
    padding: 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;

    i {
      font-size: 24px;
      margin-right: 10px;
      color: #999;
    }
  }

  // 搜索结果区域样式
  .search-results-header {
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e4e7ed;

    h4 {
      margin: 0;
      font-size: 16px;
      color: #303133;
      display: flex;
      align-items: center;
      gap: 10px;

      i {
        color: #409eff;
      }

      .el-button--text {
        margin-left: auto;
      }
    }
  }

  .quick-search-results {
    margin-bottom: 30px;

    .search-result-card {
      background: white;
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      padding: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      transition: all 0.3s;
      height: 100%;
      display: flex;
      flex-direction: column;

      &:hover {
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        transform: translateY(-2px);
        border-color: #409eff;
      }

      .result-thumbnail {
        height: 120px;
        background: #f5f7fa;
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 10px;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .text-preview {
          padding: 10px;
          font-size: 12px;
          color: #606266;
          line-height: 1.4;
          text-align: left;
          word-break: break-word;
          overflow: hidden;
          display: -webkit-box;
          -webkit-line-clamp: 5;
          -webkit-box-orient: vertical;
        }

        i {
          font-size: 36px;
          color: #909399;
        }

        .video-placeholder {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 100%;
          background: #f5f7fa;
          color: #409eff;

          i {
            font-size: 28px;
            margin-bottom: 4px;
          }

          span {
            font-size: 11px;
            color: #909399;
          }

          &.mini {
            i {
              font-size: 20px;
              margin-bottom: 2px;
            }

            span {
              font-size: 10px;
            }
          }
        }
      }

      .result-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 8px;

        .result-title {
          font-size: 14px;
          font-weight: 500;
          color: #303133;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .result-meta {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 12px;

          .stage-name {
            color: #909399;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }
    }
  }

  .el-divider {
    margin: 30px 0;
  }

  // 快速添加素材区域样式
  .quick-add-section {
    margin-top: 30px;
    padding: 20px;
    background: #f5f7fa;
    border-radius: 4px;
    border: 1px solid #e4e7ed;

    .quick-add-header {
      margin-bottom: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        margin: 0;
        font-size: 18px;
        color: #303133;

        i {
          color: #409eff;
        }
      }

      .quick-add-actions {
        display: flex;
        gap: 10px;
      }
    }

    .quick-add-form {
      margin-bottom: 20px;
    }

    .quick-add-editor {
      ::v-deep .tiptap-editor {
        background: white;
      }
    }
  }

  // 素材查看/编辑抽屉样式
  ::v-deep .el-drawer {
    .el-drawer__header {
      padding: 15px 20px;
      border-bottom: 1px solid #ebeef5;
      margin-bottom: 0;

      span {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
    }

    .el-drawer__body {
      padding: 0;
      height: calc(100vh - 60px);
      overflow: hidden;
    }

    .material-drawer-content {
      height: 100%;
      display: flex;
      flex-direction: column;

      .drawer-header {
        padding: 20px 20px 15px;
        border-bottom: 1px solid #f0f0f0;
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        gap: 20px;

        .title-section {
          flex: 1;
          min-width: 0;

          .title-input {
            ::v-deep .el-input__inner {
              font-size: 20px;
              font-weight: 600;
              border: 1px dashed #d1d5db;

              &:focus {
                border-color: #409eff;
              }
            }
          }

          .title-display {
            margin: 0;
            font-size: 20px;
            font-weight: 600;
            color: #303133;
            line-height: 1.4;
            word-break: break-word;
          }
        }

        .header-actions {
          display: flex;
          gap: 8px;
          flex-shrink: 0;
        }
      }

      .meta-info-bar {
        padding: 10px 20px;
        background: #f8f9fa;
        border-bottom: 1px solid #f0f0f0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 10px;

        .meta-left, .meta-right {
          display: flex;
          align-items: center;
          gap: 10px;
        }

        .meta-item {
          font-size: 13px;
          color: #666;
          display: flex;
          align-items: center;
          gap: 4px;

          i {
            font-size: 12px;
          }
        }

        .mini-select {
          min-width: 100px;

          &.tags-select {
            min-width: 150px;
          }
        }

        .tags-display {
          display: flex;
          flex-wrap: wrap;
          gap: 4px;
          align-items: center;

          .no-tags {
            font-size: 12px;
            color: #999;
          }
        }
      }

      .content-area {
        flex: 1;
        overflow: auto;
        padding: 20px;
        display: flex;
        gap: 20px;

        .content-main {
          flex: 1;
          min-width: 0;
        }

        .content-outline {
          width: 250px;
          min-width: 250px;
          background: #fafbfc;
          border: 1px solid #f0f0f0;
          border-radius: 6px;
          padding: 15px;
          height: fit-content;
          max-height: 600px;
          overflow-y: auto;

          .outline-header {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 15px;
            font-weight: 600;
            color: #333;
            font-size: 14px;
            border-bottom: 1px solid #e8e8e8;
            padding-bottom: 10px;

            i {
              color: #409eff;
            }
          }

          .outline-list {
            .outline-item {
              cursor: pointer;
              padding: 6px 8px;
              border-radius: 4px;
              margin-bottom: 2px;
              transition: all 0.2s ease;

              &:hover {
                background: #e8f4ff;
                color: #409eff;
              }

              .outline-text {
                font-size: 13px;
                line-height: 1.4;
                display: block;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }

              // 不同级别的标题缩进
              &.outline-level-1 {
                padding-left: 8px;
                font-weight: 600;
              }

              &.outline-level-2 {
                padding-left: 16px;
                font-weight: 500;
              }

              &.outline-level-3 {
                padding-left: 24px;
              }

              &.outline-level-4 {
                padding-left: 32px;
                font-size: 12px;
              }

              &.outline-level-5,
              &.outline-level-6 {
                padding-left: 40px;
                font-size: 12px;
                color: #666;
              }
            }
          }
        }

        .drawer-editor {
          ::v-deep .tiptap-editor {
            border: 1px solid #e4e7ed;
            border-radius: 4px;

            .editor-content {
              min-height: 500px;
              max-height: none;
            }
          }
        }

        .content-display {
          min-height: 400px;
          padding: 20px;
          background: #fafbfc;
          border: 1px solid #f0f0f0;
          border-radius: 6px;
          font-size: 14px;
          line-height: 1.6;
          color: #333;

          // 内容样式
          h1, h2, h3, h4, h5, h6 {
            margin: 20px 0 10px 0;
            &:first-child {
              margin-top: 0;
            }
          }

          p {
            margin: 0 0 12px 0;
            &:last-child {
              margin-bottom: 0;
            }
          }

          img {
            max-width: 800px;
            height: auto;

            // 手机和平板响应式
            @media (max-width: 768px) {
              max-width: 100%;
            }
            margin: 15px 0;
            border-radius: 4px;
          }

          ul, ol {
            padding-left: 24px;
            margin: 10px 0;
          }

          blockquote {
            border-left: 4px solid #409eff;
            padding-left: 16px;
            margin: 16px 0;
            color: #666;
            background: #f4f4f5;
            padding: 12px 16px;
            border-radius: 4px;
          }

          code {
            background: #f1f1f1;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: 'Courier New', monospace;
            font-size: 13px;
          }

          pre {
            background: #f8f8f8;
            padding: 16px;
            border-radius: 4px;
            overflow-x: auto;
            margin: 16px 0;
          }

          .video-wrapper {
            margin: 20px 0;
            text-align: center;

            video {
              width: 100%;
              max-width: 600px;
              height: auto;
              border: 1px solid #e4e7ed;
              border-radius: 4px;
              background: #000;
            }

            &.embed-video {
              position: relative;
              padding-bottom: 56.25%;
              height: 0;

              iframe {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                border: 0;
              }
            }
          }
        }
      }

      // 图片缩略图栏样式
      .image-thumbnail-bar {
        padding: 15px 20px;
        border-top: 1px solid #f0f0f0;
        border-bottom: 1px solid #f0f0f0;
        background: #fafbfc;
        max-height: 130px;
        overflow-y: auto;

        .thumbnail-container {
          display: flex;
          gap: 12px;
          flex-wrap: wrap;

          .thumbnail-item {
            position: relative;
            width: 100px;
            height: 100px;
            border-radius: 8px;
            overflow: hidden;
            cursor: pointer;
            border: 2px solid #e4e7ed;
            transition: all 0.3s ease;
            background: white;

            &:hover {
              border-color: #409eff;
              box-shadow: 0 2px 12px rgba(64, 158, 255, 0.2);

              .thumbnail-overlay {
                opacity: 1;
              }
            }

            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
              transition: transform 0.3s ease;
            }

            .thumbnail-overlay {
              position: absolute;
              top: 0;
              left: 0;
              right: 0;
              bottom: 0;
              background: rgba(0, 0, 0, 0.5);
              display: flex;
              align-items: center;
              justify-content: center;
              opacity: 0;
              transition: opacity 0.3s ease;

              i {
                color: white;
                font-size: 24px;
              }
            }
          }
        }
      }
    }
  }
}

// 图片查看器样式
::v-deep .image-viewer-dialog {
  .el-dialog {
    background: rgba(0, 0, 0, 0.9);
    border-radius: 8px;
  }

  .el-dialog__body {
    padding: 0;
  }

  .image-viewer {
    .viewer-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px 20px;
      background: rgba(0, 0, 0, 0.8);
      color: white;

      .image-counter {
        font-size: 16px;
        font-weight: 500;
      }

      .close-btn {
        color: white;
        font-size: 20px;

        &:hover {
          color: #409eff;
        }
      }
    }

    .viewer-content {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      min-height: 60vh;
      background: black;

      .nav-btn {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        background: rgba(0, 0, 0, 0.5);
        color: white;
        border: none;
        width: 50px;
        height: 50px;
        border-radius: 50%;
        font-size: 20px;
        z-index: 10;
        transition: all 0.3s ease;

        &:hover:not(.is-disabled) {
          background: rgba(64, 158, 255, 0.8);
          color: white;
        }

        &.is-disabled {
          color: #666;
          cursor: not-allowed;
        }

        &.prev-btn {
          left: 20px;
        }

        &.next-btn {
          right: 20px;
        }
      }

      .image-container {
        max-width: 90%;
        max-height: 80vh;
        display: flex;
        align-items: center;
        justify-content: center;

        .main-image {
          max-width: 100%;
          max-height: 100%;
          object-fit: contain;
          border-radius: 4px;
        }
      }
    }
  }
}
</style>
